//
//  ChoosePhotoViewController.m
//  ShrimpCrowdordering
//
//  Created by 郑洲 on 2018/7/25.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "ChoosePhotoViewController.h"

#import "ImageCropperViewController.h"
#import "UpdateViewController.h"

#import <Photos/Photos.h>

@interface ChoosePhotoViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, ImageCropperDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, strong) UIImage *selectImg;
@property (nonatomic, strong) UIButton *getBtn;

@end

@implementation ChoosePhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"选择图片";
    _dataArray = [NSMutableArray array];
    _selectIndex = 0;
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionInset = UIEdgeInsetsMake(ScreenX375(24), ScreenX375(24), ScreenX375(24), ScreenX375(24));
    flowLayout.minimumInteritemSpacing = ScreenX375(24);
    flowLayout.minimumLineSpacing = ScreenX375(24);
    flowLayout.itemSize = CGSizeMake((SCREEN_WIDTH - ScreenX375(74)) / 2, ScreenX375(150));
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - ScreenX375(44) - NAVIGATION_BAR_HEIGHT) collectionViewLayout:flowLayout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.alwaysBounceVertical = YES;
    [self.view addSubview:_collectionView];
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    self.getBtn = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - ScreenX375(100)) / 2, (SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(70)) / 2, ScreenX375(100), ScreenX375(40))];
    self.getBtn.layer.cornerRadius = ScreenX375(20);
    self.getBtn.layer.masksToBounds = YES;
    [self.getBtn setTitle:@"重新加载" forState:UIControlStateNormal];
    [self.getBtn setTitleColor:FONTCOLOR_BLACK forState:UIControlStateNormal];
    self.getBtn.backgroundColor = REXADECIMALCOLOR(@"#ffd100");
    [self.getBtn addTarget:self action:@selector(getPhoto) forControlEvents:UIControlEventTouchUpInside];
    self.getBtn.hidden = YES;
    [self.view addSubview:self.getBtn];
    
    [self getPhoto];
    
    UIButton *sureBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - ScreenX375(44) - NAVIGATION_BAR_HEIGHT, SCREEN_WIDTH, ScreenX375(44))];
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    sureBtn.titleLabel.font = Kfont(15);
    [sureBtn setTitleColor:REXADECIMALCOLOR(@"#ffffff") forState:UIControlStateNormal];
    [sureBtn setBackgroundImage:ImageWithName(@"按钮背景") forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(sure) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sureBtn];
}

- (void)getPhoto {
    __weak __typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableArray *arr = [self getAllPhoto];
        NSLog(@"完成%@ \n照片总数%ld", arr, arr.count);
        weakSelf.dataArray = arr;
        if (weakSelf.dataArray.count > 0) {
            PHAsset *asset = weakSelf.dataArray[0];
            [self accessToImageAccordingToTheAsset:asset size:CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT) resizeMode:PHImageRequestOptionsResizeModeNone completion:^(UIImage *image, NSDictionary *info) {
                weakSelf.selectImg = image;
            }];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            if (weakSelf.dataArray.count > 0) {
                weakSelf.getBtn.hidden = YES;
            }else {
                weakSelf.getBtn.hidden = NO;
            }
            [weakSelf.collectionView reloadData];
        });
    });
}

- (void)sure {
    ImageCropperViewController *imgEditorVC = [[ImageCropperViewController alloc] initWithImage:_selectImg cropFrame:CGRectMake(ScreenX375(33), ScreenX375(100), ScreenX375(310), ScreenX375(310)) limitScaleRatio:3.0];
    imgEditorVC.title = @"裁剪图片";
    imgEditorVC.delegate = self;
    [self.navigationController pushViewController:imgEditorVC animated:YES];
}

#pragma mark VPImageCropperDelegate
- (void)imageCropper:(ImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage{
    UpdateViewController *vc = [[UpdateViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)imageCropperDidCancel:(ImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}

- (NSMutableArray *)getAllPhoto{
    NSMutableArray *arr = [NSMutableArray array];
    // 所有智能相册
    PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    for (NSInteger i = 0; i < smartAlbums.count; i++) {
        // 是否按创建时间排序
        PHFetchOptions *option = [[PHFetchOptions alloc] init];
        option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
        option.predicate = [NSPredicate predicateWithFormat:@"mediaType == %ld", PHAssetMediaTypeImage];
        PHCollection *collection = smartAlbums[i];
        //遍历获取相册
        if ([collection isKindOfClass:[PHAssetCollection class]]) {
            if (![collection.localizedTitle isEqualToString:@"Recently Deleted"]) {
                PHAssetCollection *assetCollection = (PHAssetCollection *)collection;
                PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
                NSArray *assets;
                if (fetchResult.count > 0) {
                    // 某个相册里面的所有PHAsset对象
                    assets = [self getAllPhotosAssetInAblumCollection:assetCollection ascending:YES];
                    [arr addObjectsFromArray:assets];
                }
            }
        }
    }
    //返回相机胶卷内的所有照片
    return arr;
}

#pragma mark - <  获取相册里的所有图片的PHAsset对象  >
- (NSArray *)getAllPhotosAssetInAblumCollection:(PHAssetCollection *)assetCollection ascending:(BOOL)ascending
{
    // 存放所有图片对象
    NSMutableArray *assets = [NSMutableArray array];
    
    // 是否按创建时间排序
    PHFetchOptions *option = [[PHFetchOptions alloc] init];
    option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:ascending]];
    option.predicate = [NSPredicate predicateWithFormat:@"mediaType == %ld", PHAssetMediaTypeImage];
    
    // 获取所有图片对象
    PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:assetCollection options:option];
    // 遍历
    [result enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL * _Nonnull stop) {
        [assets addObject:asset];
    }];
    
    return assets;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString * CellIdentifier = @"cell";
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    
    for (UIView *subView in cell.subviews) {
        [subView removeFromSuperview];
    }
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, (SCREEN_WIDTH - ScreenX375(72)) / 2, ScreenX375(150))];
    PHAsset *asset = _dataArray[indexPath.item];
    [self accessToImageAccordingToTheAsset:asset size:CGSizeMake((SCREEN_WIDTH - ScreenX375(72)) / 2, ScreenX375(150)) resizeMode:PHImageRequestOptionsResizeModeExact completion:^(UIImage *image, NSDictionary *info) {
        imageView.image = image;
    }];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    [cell addSubview:imageView];
    
    UIButton *selectView = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - ScreenX375(72)) / 2 - ScreenX375(27), ScreenX375(6), ScreenX375(21), ScreenX375(21))];
    [cell addSubview:selectView];
    
    if (_selectIndex == indexPath.item) {
        [selectView setBackgroundImage:[UIImage imageNamed:@"椭圆2"] forState:UIControlStateNormal];
        [selectView setImage:[UIImage imageNamed:@"打钩"] forState:UIControlStateNormal];
    }else {
        [selectView setBackgroundImage:[UIImage imageNamed:@"椭圆1拷贝8"] forState:UIControlStateNormal];
        [selectView setImage:nil forState:UIControlStateNormal];
    }
    
    return cell;
}

- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    _selectIndex = indexPath.item;
    PHAsset *asset = _dataArray[_selectIndex];
    [self accessToImageAccordingToTheAsset:asset size:CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT) resizeMode:PHImageRequestOptionsResizeModeNone completion:^(UIImage *image, NSDictionary *info) {
        self.selectImg = image;
    }];
    [_collectionView reloadData];
}

#pragma mark - <  根据PHAsset获取图片信息  >
- (void)accessToImageAccordingToTheAsset:(PHAsset *)asset size:(CGSize)size resizeMode:(PHImageRequestOptionsResizeMode)resizeMode completion:(void(^)(UIImage *image,NSDictionary *info))completion
{
    static PHImageRequestID requestID = -2;
    
    CGFloat scale = [UIScreen mainScreen].scale;
    CGFloat width = MIN([UIScreen mainScreen].bounds.size.width, 500);
    if (requestID >= 1 && size.width / width == scale) {
        [[PHCachingImageManager defaultManager] cancelImageRequest:requestID];
    }
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    option.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;
    //    option.resizeMode = PHImageRequestOptionsResizeModeFast;
    option.resizeMode = resizeMode;
    
    requestID = [[PHCachingImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeAspectFill options:option resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        dispatch_async(dispatch_get_main_queue(), ^{
            completion(result,info);
        });
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
@end
